package com.party.mem.biz.member;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.redis.StringJedis;
import com.party.common.utils.DateUtils;
import com.party.common.utils.StringUtils;
import com.party.core.dao.read.member.PartnerMemberReadDao;
import com.party.core.model.YesNoStatus;
import com.party.core.model.gatherForm.GatherForm;
import com.party.core.model.gatherForm.GatherFormInfo;
import com.party.core.model.gatherForm.GatherProject;
import com.party.core.model.member.MemberMgmtQuery;
import com.party.core.model.member.PartnerMember;
import com.party.core.model.system.RoleEnum;
import com.party.core.service.gatherForm.IGatherFormInfoService;
import com.party.core.service.gatherForm.IGatherFormService;
import com.party.core.service.gatherForm.IGatherProjectService;
import com.party.core.service.gatherForm.biz.GatherProjectBizService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.picCloud.CosCloudBizService;
import com.party.core.service.system.ISysRoleService;
import com.party.file.cos.dto.UploadResult;
import com.party.file.cos.meta.InsertOnly;
import com.party.mem.biz.system.member.MemberGroupBizService;
import com.party.mem.utils.RealmUtils;
import com.party.mem.utils.excel.ExportExcel;
import com.party.mem.web.dto.output.member.MemberMgmtOutput;
import com.party.mem.web.security.CurrentUser;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 会员管理业务
 * @Author: yangshoukun
 * @Date: 2018/2/22 11:52
 */
@Service
public class MemberMgmtService {

    private String uploadPath = Constant.UPLOAD_EXCEL;

    @Autowired
    private StringJedis stringJedis;

    private static final String REDIS_LIST_KEY = "export_excel_list";

    @Autowired
    private CosCloudBizService cosCloudBizService;

    @Autowired
    private IGatherFormService gatherFormService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private MemberGroupBizService memberGroupBizService;

    @Autowired
    private IMemberGroupService memberGroupService;

    @Autowired
    private IGatherProjectService gatherProjectService;

    @Autowired
    private IGatherFormInfoService gatherFormInfoService;
    @Autowired
    private GatherProjectBizService gatherProjectBizService;


    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PartnerMemberReadDao partnerMemberReadDao;

    public List<Map<String, Object>> list(MemberMgmtQuery input, String partnerId, Page page) {
        convertDate(input);
        return partnerMemberReadDao.listByPartnerId3(input, partnerId, page);
    }

    private void convertDate(MemberMgmtQuery input) {
        if (null == input || null == input.getTimeType() || 0 ==input.getTimeType()) {
            return;
        }
        Integer timeType = input.getTimeType();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        Date ed = calendar.getTime(); // 结束时间
        if (input.getTimeType() == 2) { // 本周内
            int day_of_week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
            if (day_of_week == 0) {
                day_of_week = 7;
            }
            calendar.add(Calendar.DATE, -day_of_week + 1);
        } else if (input.getTimeType() == 3) { // 本月内
            calendar.set(Calendar.DAY_OF_MONTH, 1);
        } else if (input.getTimeType() == 4) { // 昨天
            calendar.add(Calendar.DATE, -1);
            ed = calendar.getTime();
        }
        Date sd = calendar.getTime(); // 开始时间
        String std = sdf.format(sd) + " 00:00:00";
        input.setCreateStart(std);
        String end = sdf.format(ed) + " 23:59:59";
        input.setCreateEnd(end);
    }


    /**
     * 设置导出内容
     * @param list 输出列表
     * @param exportExcel 导出excel
     * @return 导出excel
     * @Author: huangwuming
     * @Date: 2018/2/27 10:56
     */
    public ExportExcel setDataList(List<Map<String, Object>> list, ExportExcel exportExcel,
                                   MemberMgmtQuery input, List<String> titles){
        for (Map analyzeOutput : list){
            Row row = exportExcel.addRow();
            String userSerial = (String) analyzeOutput.get("userSerial");
            String nickName = (String) analyzeOutput.get("nickName");
            String sex = (String) analyzeOutput.get("sex");
            String mobile = (String) analyzeOutput.get("mobile");
            String wechatNum = (String) analyzeOutput.get("wechatNum");
            String company = (String) analyzeOutput.get("company");
            String area = (String) analyzeOutput.get("area");
            String job = (String) analyzeOutput.get("job");
            String createTime = (String) analyzeOutput.get("createTime");
            String realname = (String) analyzeOutput.get("realname");
            //分社职务
            String leagueJob = (String) analyzeOutput.get("leagueJob");
            //最近参加活动时间
            String lastJoinActTime = (String) analyzeOutput.get("lastJoinActTime");
            //推荐人数
            String memRecommends = String.valueOf(analyzeOutput.get("memRecommends")== null ?
                                    0 : analyzeOutput.get("memRecommends")) ;
            //行动力
            String memberActionForce = String.valueOf(analyzeOutput.get("memberActionForce") == null ?
                                    0 : analyzeOutput.get("memberActionForce")) ;
            //影响力
            String memberInfluenceForce = String.valueOf(analyzeOutput.get("memberInfluenceForce") == null ?
                                    0 : analyzeOutput.get("memberInfluenceForce"));
            //户外积分
            String outdoorIntegral = String.valueOf(analyzeOutput.get("outdoorIntegral") == null ?
                                    0 : analyzeOutput.get("outdoorIntegral"));
            //贡献积分
            String devoteIntegral = String.valueOf(analyzeOutput.get("devoteIntegral") == null ?
                                    0 : analyzeOutput.get("devoteIntegral"));
            //学习积分
            String studyIntegral = String.valueOf(analyzeOutput.get("studyIntegral") == null ?
                                    0 : analyzeOutput.get("studyIntegral"));
            //公益积分
            String publicWelfareIntegral = String.valueOf(analyzeOutput.get("publicWelfareIntegral") == null ?
                                    0 : analyzeOutput.get("publicWelfareIntegral"));

            // row样式
            CellStyle cellStyle = exportExcel.getWb().createCellStyle();

            exportExcel.addCell(row, 0, userSerial, cellStyle);
            exportExcel.addCell(row, 1, nickName, cellStyle);
            exportExcel.addCell(row, 2, sex, cellStyle);
            exportExcel.addCell(row, 3, mobile, cellStyle);
            exportExcel.addCell(row, 4, wechatNum, cellStyle);
            exportExcel.addCell(row, 5, company, cellStyle);
            exportExcel.addCell(row, 6, area, cellStyle);
            exportExcel.addCell(row, 7, job, cellStyle);
            exportExcel.addCell(row, 8, createTime,cellStyle);
            exportExcel.addCell(row, 9, realname,cellStyle);

            if (input.getType().equals(0)) {
                String checkStatusName = "";
                Object tempCheckStatus = analyzeOutput.get("checkStatus");
                if (null != tempCheckStatus) {
                    Integer checkStatus = (Integer) tempCheckStatus;
                    if (new Integer(0).equals(checkStatus)) {
                        checkStatusName = "待审核";
                    } else if (new Integer(1).equals(checkStatus)) {
                        checkStatusName = "审核通过";
                    } else {
                        checkStatusName = "审核拒绝";
                    }
                }
                exportExcel.addCell(row, 10, checkStatusName, cellStyle);
            }

            exportExcel.addCell(row, 11, leagueJob,cellStyle);
            exportExcel.addCell(row, 12, lastJoinActTime,cellStyle);
            exportExcel.addCell(row, 13, memberActionForce,cellStyle);
            exportExcel.addCell(row, 14, memberInfluenceForce,cellStyle);
            exportExcel.addCell(row, 15, outdoorIntegral,cellStyle);
            exportExcel.addCell(row, 16, publicWelfareIntegral,cellStyle);
            exportExcel.addCell(row, 17, devoteIntegral,cellStyle);
            exportExcel.addCell(row, 18, studyIntegral,cellStyle);
            exportExcel.addCell(row, 19, memRecommends,cellStyle);

            //自定义表单值
            if (titles != null) {
                Integer column = Integer.valueOf(19);
                for (String title : titles) {
                    String value = (String) analyzeOutput.get(title);
                    column +=1;
                    exportExcel.addCell(row, column, value, cellStyle);
                }
            }

/*            if(input.getType() == 0) {
                exportExcel.addCell(row, 8, projecNum, cellStyle);
                exportExcel.addCell(row, 9, totalMoney, cellStyle);
            }
            if(input.getType() == 1){
                exportExcel.addCell(row, 8, supportMoney,cellStyle);
            }*/
        }
        return exportExcel;
    }
    /**
     * 上传excel
     *
     * @param fileName    文件名
     * @param exportPath  目录
     * @param exportExcel 文件
     * @return
     */
    public synchronized String getExcelPath(String fileName, String exportPath, ExportExcel exportExcel) throws IOException {
        String suffix = DateUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS");
        if (fileName.indexOf(".xlsx") != -1) {
            fileName = fileName.substring(0, fileName.indexOf(".xlsx")) + '-' + suffix + ".xlsx";
        } else if (fileName.indexOf(".xls") != -1) {
            fileName = fileName.substring(0, fileName.indexOf(".xls")) + '-' + suffix + ".xls";
        }
        try {
            exportPath = String.format(uploadPath, exportPath, fileName);
            InputStream inputStream = exportExcel.newUploadCloud();
            UploadResult uploadResult = cosCloudBizService.uploadFile(inputStream, exportPath, InsertOnly.NO_OVER_WRITE);
            String resourceUrl = uploadResult.getSourceUrl();
            pushRedis(resourceUrl);
            return resourceUrl;
        } catch (Exception e) {
            logger.error("上传Excel到腾讯云异常：cloudFilePath——" + exportPath + "；cloudFileName——" + fileName, e);
        }
        return null;
    }
    public void pushRedis(String resourceUrl) {
        try {
            resourceUrl = URLDecoder.decode(resourceUrl, Constant.UTF_8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        List<Map> mapList = getRedisAll();
        Map<String, Object> map = Maps.newHashMap();
        map.put(resourceUrl, DateUtils.formatDate(new Date(), DateUtils.DATE_PATTERN));
        mapList.add(map);
        stringJedis.setValue(REDIS_LIST_KEY, JSONObject.toJSONString(mapList));
    }
    public List<Map> getRedisAll() {
        List<Map> mapList = Lists.newArrayList();
        String result = stringJedis.getValue(REDIS_LIST_KEY);
        if (StringUtils.isNotEmpty(result)) {
            mapList = JSONArray.parseArray(result, Map.class);
        }
        return mapList;
    }




    public Long getMemberCountByOrgIds(List<String> orgIds) {
        return partnerMemberReadDao.getMemberCountByOrgIds(orgIds);
    }

    public boolean hasZxgsPartner(String partnerId,String memberId) {
        boolean result = false;

        boolean b = sysRoleService.hasRole(partnerId, RoleEnum.KNOWING_COMMUNE_ROLE.getCode());
        if (!b) {
            return result;
        } else {
            String xzgsMemberId = memberGroupBizService.getXzgsMemberId();
            HashMap<String, Object> params = Maps.newHashMap();

            List<String> orgIds = memberGroupService.getChild(xzgsMemberId);

            params.put("memberId",memberId);
            params.put("partnerIds",orgIds);
            List<PartnerMember> partners = partnerMemberReadDao.getMemberPartnersTo(params);

            if (partners.size() > 0) {
                result = true;
            } else {
                result = false;
            }
            return result;
        }

    }

    public MemberMgmtOutput getMemberCompanyInfo(PartnerMember partnerMember) {

        MemberMgmtOutput mgmtOutput = new MemberMgmtOutput();

        MemberMgmtQuery input = new MemberMgmtQuery();
        String partnerId = memberGroupService.getPartnerId(partnerMember.getPartnerId());
        String projectBy = partnerId + "kc";

        GatherProject project = gatherProjectService.findByCreateIdAndType(GatherProject.TYPE_KC_MEMBER, projectBy);

        if (null == input.getType()) {
            input.setType(0);
        }
        //自定义表单项业务
        List<String> titles = new ArrayList<>();
        if (project != null && input.getType() != Integer.valueOf(1)) {
            input.setProjectId(project.getId());
            titles = gatherFormService.getAllTitleByProjectId(project.getId());
            input.setTitles(titles);
        }
        String xzgsMemberId = memberGroupBizService.getXzgsMemberId();
        input.setXzgsMemberId(xzgsMemberId);

        input.setMemberId(partnerMember.getMemberId());
        List<Map<String, Object>> output = list(input, partnerMember.getPartnerId(), null);

        Map<String, Object> map = output.get(0);

        if (titles != null) {
            Map<String, Object> customField = new LinkedHashMap<>();
            for (String title : titles) {
                customField.put(title, map.get(title) == null ? "" : map.get(title));
            }
            mgmtOutput.setCustomField(customField);
        }

        return mgmtOutput;
    }

    /**
     * 获取自定义表单项
     *
     * @return java.util.List<java.lang.String>
     * @author shenliuhai
     * @date 2019/12/13 17:48
     */
    public List<String> titleList() {

        List<String> titles = new ArrayList<>();

        CurrentUser member = RealmUtils.getNewCurrentUser();

        String projectBy = memberGroupService.getPartnerId(member.getId()) + "kc";

        GatherProject project = gatherProjectService.findByCreateIdAndType(GatherProject.TYPE_KC_MEMBER, projectBy);

        if (project != null) {
            titles = gatherFormService.getAllTitleByProjectId(project.getId());
        }
        return titles;
    }

    /**
     * 获取问卷调查信息
     * @author shenliuhai
     * @date 2020/1/19 14:28
     * @param
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    public void getQuestionInfo(ModelAndView mv, String memberId) {
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();

        String parentId = memberGroupService.getPartnerId(currentUser.getId());
        Map<String,Object> params = Maps.newHashMap();

        String creatrBy = parentId + "QA";
        //获取问卷调查项目id

        GatherProject byCreateIdAndType =
                gatherProjectService.findByCreateIdAndType(GatherProject.TYPE_QUESTIONNAIRE, creatrBy);
        String projectId = "";
        if (byCreateIdAndType != null) {
            projectId = byCreateIdAndType.getId();
        }

        GatherProject project = gatherProjectService.get(projectId);
        boolean isNew = true;
        if (project != null) {
            List<GatherForm> fieldName = gatherProjectBizService.getFormItems(projectId, true);
            List<GatherFormInfo> fieldValue = gatherFormInfoService.getFormInfoByMemberId(memberId, projectId);
            if (fieldValue.size() > 0) {
                isNew = false;
            }
            mv.addObject("fieldName", fieldName);
            mv.addObject("fieldValue", fieldValue);
            mv.addObject("isNew", isNew);
        }
        mv.addObject("memberId",memberId);
        mv.addObject("projectId", projectId);
    }
}
